import requests
import json
import os
from datetime import datetime

# 飞书应用配置 - 从Gitee Go的环境变量中获取
APP_ID = os.environ.get('FEISHU_APP_ID', 'cli_a87a121fd800d013')  # 此处可写死，但更推荐用环境变量
APP_SECRET = os.environ.get('FEISHU_APP_SECRET', 'mqy8Re8wOoLftbeaMZMgvgnwAB7wSDQY')

def get_tenant_token():
    """获取飞书tenant_access_token"""
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    headers = {'Content-Type': 'application/json'}
    data = {'app_id': APP_ID, 'app_secret': APP_SECRET}
    
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
        result = response.json()
        if result.get('code') == 0:
            return result['tenant_access_token']
        else:
            print(f"Error fetching token: {result.get('msg')}")
            return f"Error: {result.get('msg')}"
    except Exception as e:
        print(f"Request failed: {e}")
        return f"Request Error: {str(e)}"

def update_html(token):
    """用新的token更新HTML文件"""
    with open('index.html', 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 替换占位符
    new_content = content.replace('##TOKEN##', token)
    new_content = new_content.replace('##UPDATE_TIME##', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    
    with open('index.html', 'w', encoding='utf-8') as f:
        f.write(new_content)
    print("HTML file updated successfully.")

if __name__ == '__main__':
    token = get_tenant_token()
    update_html(token)